from flask import Blueprint, render_template, \
    current_app, request, flash, redirect, url_for
from flask_login import login_required
from app.extensions import db
from app.models import User
from app.forms import UserForm

bp = Blueprint('users', __name__)


@bp.before_request
@login_required
def before_request():
    pass


@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    pre_page = current_app.config['POST_PRE_PAGE']
    pagination = User.query.paginate(page, pre_page)
    return render_template(
        'manage/users/index.html',
        model=pagination.items,
        page=page,
        pagination=pagination)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    form = UserForm()
    return render_template('manage/users/update.html', form=form)


@bp.route('/delete/<int:id>')
def delete(id):
    user = User.query.get_or_404(id)
    db.session.delete(user)
    db.session.commit()
    flash('删除成功!', 'success')
    return redirect(url_for('users.index'))
